// Copyright © SixtyFPS GmbH <info@slint.dev>
// SPDX-License-Identifier: GPL-3.0-only OR LicenseRef-Slint-Royalty-free-2.0 OR LicenseRef-Slint-Software-3.0

import { CosmicFontSettings, CosmicPalette, Icons } from "styling.slint";
import { StateLayer } from "components.slint";

export component CheckBox {
    in property <string> text;
    in property <bool> enabled <=> state-layer.enabled;
    out property <bool> has-focus: state-layer.has-focus;
    in-out property <bool> checked;

    callback toggled;

    private property <color> text-color: CosmicPalette.foreground;

    min-height: max(16px, layout.min-height);
    accessible-enabled: root.enabled;
    accessible-checkable: true;
    accessible-label: root.text;
    accessible-checked <=> root.checked;
    accessible-role: checkbox;
    accessible-action-default => { state-layer.clicked(); }
    forward-focus: state-layer;

    states [
        disabled when !root.enabled : {
           opacity: 0.5;
        }
        checked when root.checked && root.enabled : {
            background.background: CosmicPalette.accent-background;
        }
    ]

    animate text-color { duration: 200ms; }

    touch-area := TouchArea {
        enabled: root.enabled;

        clicked => {
            state-layer.clicked();
        }
    }

    layout := HorizontalLayout {
        spacing: 8px;

        background := Rectangle {
            width: 16px;
            height: self.width;
            y: (parent.height - self.height) / 2;
            background: CosmicPalette.control-background;
            border-radius: 4px;

            animate background, border-color { duration: 150ms; }

            border := Rectangle {
                border-color: CosmicPalette.alternate-border;
                border-width: root.checked ? 0 : 1px;
                border-radius: parent.border-radius;
            }

            icon := Image {
                image-fit: contain;
                visible: root.checked;
                source: Icons.check-mark;
                colorize: CosmicPalette.accent-foreground;
                width: 12px;
                accessible-role: none;

                animate colorize { duration: 150ms; }
            }

            state-layer := StateLayer {
                border-radius: background.border-radius;

                clicked => {
                    if (root.enabled) {
                        root.checked = !root.checked;
                        root.toggled();
                    }
                }
            }
        }

        if (root.text != "") : Text {
            text: root.text;
            color: root.text-color;
            font-size: CosmicFontSettings.body.font-size;
            font-weight: CosmicFontSettings.body.font-weight;
            vertical-alignment: center;
            horizontal-alignment: left;
        }
    }
}
